package com.ljj.examisto.data.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.ljj.examisto.R
import com.ljj.examisto.data.item.SettingBlock
import com.ljj.examisto.databinding.ItemSettingBlockBinding
import com.ljj.examisto.util.Logger.TAG

class SettingAdapter(private val settingBlocks: List<SettingBlock>) : RecyclerView.Adapter<SettingAdapter.SettingBlockViewHolder>() {
    inner class SettingBlockViewHolder(private val binding: ItemSettingBlockBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(block: SettingBlock) {
            binding.blockTitle.text = block.category
            // 清空之前的选项
            binding.blockOptions.removeAllViews()
            // 动态添加每个 SettingOption 到 LinearLayout 中
            for (option in block.options) {
                val optionView = LayoutInflater.from(binding.root.context)
                    .inflate(R.layout.item_setting_option, binding.blockOptions, false)
                // 获取视图引用
                val titleTextView = optionView.findViewById<TextView>(R.id.option_title)
                val widgetContainer = optionView.findViewById<FrameLayout>(R.id.option_widget)
                // 设置option标题
                titleTextView.text = option.title
                // 设置optionUI控件
                widgetContainer.addView(option.uiWidget)
                // 把option添加到block
                binding.blockOptions.addView(optionView)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingBlockViewHolder {
        val binding = ItemSettingBlockBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return SettingBlockViewHolder(binding)
    }

    override fun onBindViewHolder(holder: SettingBlockViewHolder, position: Int) {
        holder.bind(settingBlocks[position])
    }

    override fun getItemCount(): Int = settingBlocks.size

    fun getWidget(title: String): View? {
        for (block in settingBlocks) {
            for (option in block.options) {
                if (option.title == title) {
                    return option.uiWidget
                }
            }
        }
        Log.d(TAG, "getWidget: 未找到控件")
        return null
    }
}